﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private static GameManager instance;
    public static GameManager Instance => instance;

    [Header("是否GM解锁关卡")]
    public bool isUnLockLevel;

    [Header("解锁到第几关")]
    public int level;

    [Space(10)]
    [SerializeField]
    private GameObject levelGenerator;


    [SerializeField]
    private AudioSource bgmAS;

    [SerializeField]
    private AudioSource soundAS;

    [SerializeField]
    private AudioClip mainMenuClip;

    [SerializeField]
    private AudioClip gameClip;

    [SerializeField]
    private AudioClip switchBtnClip;

    [SerializeField]
    private AudioClip victoryClip;

    [SerializeField]
    private AudioClip normalBtnClip;

    [SerializeField]
    private AudioClip targetClip;

    /// <summary>
    /// 播放主界面BGM
    /// </summary>
    public void PlayerMainMenuBGM()
    {
        if (bgmAS.clip == mainMenuClip)
            return;
        bgmAS.clip = mainMenuClip;
        bgmAS.Play();
    }

    /// <summary>
    /// 播放游戏中BGM
    /// </summary>
    public void PlayerGameBGM()
    {
        if (bgmAS.clip == gameClip)
            return;
        bgmAS.clip = gameClip;
        bgmAS.Play();
    }

    /// <summary>
    /// 播放开关按钮音效
    /// </summary>
    public void PlaySwitchBtnSound()
    {
        soundAS.clip = switchBtnClip;
        soundAS.Play();
    }

    /// <summary>
    /// 播放通关音效
    /// </summary>
    public void PlayVictoryClip()
    {
        soundAS.clip = victoryClip;
        soundAS.Play();
    }

    /// <summary>
    /// 播放普通按钮音效
    /// </summary>
    public void PlayNormalBtnClip()
    {
        soundAS.clip = normalBtnClip;
        soundAS.Play();
    }

    /// <summary>
    /// 播放获取条件音效
    /// </summary>
    public void PlayTargetClip()
    {
        soundAS.clip = targetClip;
        soundAS.Play();
    }

    /// <summary>
    /// 关卡通关存储数据  若不存在，但又确实有关卡的，为未解锁关卡
    /// key: 关卡
    /// value: 0表示未锁定 1表示通关 -1表示锁定关卡
    /// </summary>
    private Dictionary<int, int> levelSaveDict;

    private void Awake()
    {
        if (instance == null)
            instance = this;
        Application.targetFrameRate = 60;
        ReadInfo();
        ReadMusicInfo();
    }

    /// <summary>
    /// 读取音乐信息
    /// </summary>
    private void ReadMusicInfo()
    {
        float bgmVolume = PlayerPrefs.GetFloat("BgmVolume", 0.2f);
        float soundVolume = PlayerPrefs.GetFloat("SoundVolume", 0.2f);
        bgmAS.volume = bgmVolume;
        soundAS.volume = soundVolume;
    }

    /// <summary>
    /// 设置BGM音量
    /// </summary>
    /// <param name="varVolume">音量</param>
    public void SetBgmVolume(float varVolume)
    {
        bgmAS.volume = varVolume;
    }

    /// <summary>
    /// 设置音效音量
    /// </summary>
    /// <param name="varVolume">音量</param>
    public void SetSoundVolume(float varVolume)
    {
        soundAS.volume = varVolume;
    }

    /// <summary>
    /// 存储声音设置
    /// </summary>
    public void SaveMusciSetting()
    {
        PlayerPrefs.SetFloat("BgmVolume", bgmAS.volume);
        PlayerPrefs.SetFloat("SoundVolume", soundAS.volume);
        PlayerPrefs.Save();
    }

    /// <summary>
    /// 读取存档信息
    /// </summary>
    private void ReadInfo()
    {
        if (levelSaveDict != null)
            return;
        levelSaveDict = new Dictionary<int, int>();
        string saveStr = "1,0";
        if (isUnLockLevel)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < level; i++)
            {
                if (i != 0)
                {
                    sb.Append("|");
                }

                sb.Append($"{i + 1},0");
            }

            saveStr = sb.ToString();
        }
        string saveData = PlayerPrefs.GetString("SaveData", saveStr);
        PlayerPrefs.SetString("SaveData", saveData.ToString());
        string[] levelArr = saveData.Split('|');
        for (int i = 0; i < levelArr.Length; i++)
        {
            string[] arr = levelArr[i].Split(',');
            int templevel = Convert.ToInt32(arr[0]);
            int status = Convert.ToInt32(arr[1]);
            levelSaveDict[templevel] = status;
        }
    }

    /// <summary>
    /// 获取关卡状态
    /// </summary>
    /// <param name="level">关卡</param>
    /// <returns>关卡状态</returns>
    public ELevelStatus GetLevelStatus(int level)
    {
        if (levelSaveDict.ContainsKey(level))
        {
            switch (levelSaveDict[level])
            {
                case -1: return ELevelStatus.Lock;
                case 0: return ELevelStatus.UnLock;
                case 1: return ELevelStatus.Pass;
            }
        }

        return ELevelStatus.Lock;
    }


    /// <summary>
    /// 存储数据  存储通关数据时，会默认将下一关设置为已解锁
    /// </summary>
    /// <param name="level">关卡</param>
    /// <param name="levelStatus">关卡状态</param>
    public void SaveData(int level, ELevelStatus levelStatus)
    {
        levelSaveDict[level] = (int) levelStatus;
        if (levelStatus == ELevelStatus.Pass)
        {
            if (!levelSaveDict.ContainsKey(level + 1) || levelSaveDict[level + 1] != (int) ELevelStatus.Pass)
                levelSaveDict[level + 1] = (int) ELevelStatus.UnLock;
        }

        bool isStart = true;
        StringBuilder sb = new StringBuilder();
        foreach (var singleLevelItem in levelSaveDict)
        {
            if (!isStart)
            {
                sb.Append("|");
            }

            string key = singleLevelItem.Key.ToString();
            string value = singleLevelItem.Value.ToString();
            sb.Append($"{key},{value}");
            isStart = false;
        }

        PlayerPrefs.SetString("SaveData", sb.ToString());
    }

    /// <summary>
    /// 创建关卡生成器
    /// </summary>
    public void CreateLevelGenerator()
    {
        Instantiate(levelGenerator);
    }
}